package com.gl.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.entity.SystemDict;
import com.gl.order.entity.dto.SysDictAddDto;
import com.gl.order.entity.dto.SysDictEditDto;
import com.gl.order.mapper.SystemDictMapper;
import com.gl.order.service.SystemDictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liangSY
 * @Date: 2021/6/23 8:53
 * @ClassName: SystemDictServiceImpl
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SystemDictServiceImpl extends ServiceImpl<SystemDictMapper, SystemDict> implements SystemDictService {

    @Override
    public List<SystemDict> findByTypeNot(String type) {
        LambdaQueryWrapper<SystemDict> queryWrapper = Wrappers.lambdaQuery();
        List<SystemDict> dict = this.baseMapper.selectList(queryWrapper.ne(SystemDict::getType, type));
        return dict;
    }

    @Override
    public void addSysDict(SysDictAddDto dto) {
        SystemDict dict = new SystemDict();
        BeanUtils.copyProperties(dto,dict);
        save(dict);
    }

    @Override
    public List findByType(String type) {
        LambdaQueryWrapper<SystemDict> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SystemDict::getId,SystemDict::getName,SystemDict::getRemark);
        if(StringUtils.isNotBlank(type)){
            queryWrapper.eq(SystemDict::getType,type);
        }
        List<SystemDict> list = list(queryWrapper);
        return list;
    }

    @Override
    public Map findByMenuPath(String menuPath) {
        List<SystemDict> list = this.baseMapper.findByMenuPath(menuPath);
        HashMap<String, List<SystemDict>> map = list.stream().collect(Collectors.groupingBy(SystemDict::getType, HashMap::new, Collectors.toList()));
        return map;
    }

    @Override
    public void updateByDto(SysDictEditDto dto) {
        SystemDict check = getById(dto.getId());
        Assert.isNull(check, "Target must not be null");
        SystemDict dict = new SystemDict();
        BeanUtils.copyProperties(dto,dict);
        updateById(dict);
    }

}
